package com.rickpan.controller;

import com.rickpan.annotation.VipFeature;
import com.rickpan.dto.common.ApiResponse;
import com.rickpan.dto.request.GenerateReportRequest;
import com.rickpan.dto.request.SaveReportRequest;
import com.rickpan.dto.response.GeneratedReportResponse;
import com.rickpan.dto.response.WorkRecordResponse;
import com.rickpan.service.WorkRecordService;
import com.rickpan.service.WorkReportGenerationService;
import com.rickpan.utils.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

/**
 * 工作报告生成控制器
 */
@RestController
@RequestMapping("/api/work-reports")
@Tag(name = "工作报告生成", description = "AI工作报告生成相关接口")
public class WorkReportController {

    private static final Logger logger = LoggerFactory.getLogger(WorkReportController.class);

    @Autowired
    private WorkReportGenerationService reportGenerationService;

    @Autowired
    private WorkRecordService workRecordService;



    /**
     * 生成工作报告
     */
    @PostMapping("/generate")
    @VipFeature(value = "AI_REPORT", description = "AI工作报告生成")
    @Operation(summary = "生成工作报告", description = "根据工作记录生成AI工作报告")
    public ApiResponse<GeneratedReportResponse> generateReport(
            HttpServletRequest request,
            @Valid @RequestBody GenerateReportRequest generateRequest) {
        
        Long userId = SecurityUtils.getCurrentUserId();
        logger.info("生成工作报告，用户ID: {}, 类型: {}, 开始日期: {}, 结束日期: {}", 
                   userId, generateRequest.getType(), generateRequest.getStartDate(), generateRequest.getEndDate());

        // 验证日期范围
        generateRequest.validateDateRange();

        String reportContent;
        LocalDate startDate = generateRequest.getStartDate();
        LocalDate endDate = generateRequest.getEndDate();

        // 根据报告类型生成报告
        switch (generateRequest.getType()) {
            case DAILY:
                reportContent = reportGenerationService.generateDailyReport(userId, startDate, generateRequest);
                endDate = startDate; // 日报的结束日期等于开始日期
                break;
            case WEEKLY:
                reportContent = reportGenerationService.generateWeeklyReport(userId, startDate, endDate, generateRequest);
                break;
            case MONTHLY:
                reportContent = reportGenerationService.generateMonthlyReport(userId, startDate, endDate, generateRequest);
                break;
            default:
                throw new IllegalArgumentException("不支持的报告类型: " + generateRequest.getType());
        }

        // 获取统计信息
        List<WorkRecordResponse> records = workRecordService.getWorkRecordsByDateRange(userId, startDate, endDate);
        int totalTimeSpent = records.stream().mapToInt(r -> r.getTimeSpent() != null ? r.getTimeSpent() : 0).sum();

        // 构建响应
        GeneratedReportResponse response = new GeneratedReportResponse(
                generateRequest.getType(), startDate, endDate, reportContent);
        response.setRecordCount(records.size());
        response.setTotalTimeSpent(totalTimeSpent);

        logger.info("工作报告生成成功，用户ID: {}, 记录数: {}, 总耗时: {}分钟", userId, records.size(), totalTimeSpent);
        return ApiResponse.success(response, "工作报告生成成功");
    }

    /**
     * 保存报告到历史记录
     */
    @PostMapping("/save")
    @Operation(summary = "保存报告到历史记录", description = "将生成的报告保存到历史记录中")
    public ApiResponse<Long> saveReportToHistory(
            HttpServletRequest request,
            @Valid @RequestBody SaveReportRequest saveRequest) {

        Long userId = SecurityUtils.getCurrentUserId();
        logger.info("保存报告到历史记录，用户ID: {}, 类型: {}, 标题: {}",
                   userId, saveRequest.getType(), saveRequest.getTitle());

        // 保存报告
        Long reportId = reportGenerationService.saveReportToHistory(
                userId,
                saveRequest.getType(),
                saveRequest.getStartDate(),
                saveRequest.getEndDate(),
                saveRequest.getContent(),
                saveRequest.getTitle()
        );

        logger.info("报告保存成功，报告ID: {}", reportId);
        return ApiResponse.success(reportId, "报告保存成功");
    }

    /**
     * 快速生成今日日报
     */
    @PostMapping("/generate/daily")
    @VipFeature(value = "AI_REPORT", description = "AI工作报告生成")
    @Operation(summary = "生成今日日报", description = "快速生成今日工作日报")
    public ApiResponse<GeneratedReportResponse> generateTodayReport(
            @RequestBody(required = false) GenerateReportRequest settings,
            HttpServletRequest request) {
        Long userId = SecurityUtils.getCurrentUserId();
        LocalDate today = LocalDate.now();

        logger.info("生成今日日报，用户ID: {}, 日期: {}", userId, today);

        String reportContent = reportGenerationService.generateDailyReport(userId, today, settings);
        
        // 获取统计信息
        List<WorkRecordResponse> records = workRecordService.getWorkRecordsByDate(userId, today);
        int totalTimeSpent = records.stream().mapToInt(r -> r.getTimeSpent() != null ? r.getTimeSpent() : 0).sum();

        // 构建响应
        GeneratedReportResponse response = new GeneratedReportResponse(
                GenerateReportRequest.ReportType.DAILY, today, today, reportContent);
        response.setRecordCount(records.size());
        response.setTotalTimeSpent(totalTimeSpent);

        return ApiResponse.success(response, "今日日报生成成功");
    }

    /**
     * 快速生成本周周报
     */
    @PostMapping("/generate/weekly")
    @Operation(summary = "生成本周周报", description = "快速生成本周工作周报")
    public ApiResponse<GeneratedReportResponse> generateThisWeekReport(HttpServletRequest request) {
        Long userId = SecurityUtils.getCurrentUserId();
        
        // 计算本周的开始和结束日期（周一到周日）
        LocalDate today = LocalDate.now();
        LocalDate startOfWeek = today.minusDays(today.getDayOfWeek().getValue() - 1);
        LocalDate endOfWeek = startOfWeek.plusDays(6);
        
        logger.info("生成本周周报，用户ID: {}, 开始日期: {}, 结束日期: {}", userId, startOfWeek, endOfWeek);

        String reportContent = reportGenerationService.generateWeeklyReport(userId, startOfWeek, endOfWeek);
        
        // 获取统计信息
        List<WorkRecordResponse> records = workRecordService.getWorkRecordsByDateRange(userId, startOfWeek, endOfWeek);
        int totalTimeSpent = records.stream().mapToInt(r -> r.getTimeSpent() != null ? r.getTimeSpent() : 0).sum();

        // 构建响应
        GeneratedReportResponse response = new GeneratedReportResponse(
                GenerateReportRequest.ReportType.WEEKLY, startOfWeek, endOfWeek, reportContent);
        response.setRecordCount(records.size());
        response.setTotalTimeSpent(totalTimeSpent);

        return ApiResponse.success(response, "本周周报生成成功");
    }

    /**
     * 快速生成本月月报
     */
    @PostMapping("/generate/monthly")
    @Operation(summary = "生成本月月报", description = "快速生成本月工作月报")
    public ApiResponse<GeneratedReportResponse> generateThisMonthReport(HttpServletRequest request) {
        Long userId = SecurityUtils.getCurrentUserId();
        
        // 计算本月的开始和结束日期
        LocalDate today = LocalDate.now();
        LocalDate startOfMonth = today.withDayOfMonth(1);
        LocalDate endOfMonth = today.withDayOfMonth(today.lengthOfMonth());
        
        logger.info("生成本月月报，用户ID: {}, 开始日期: {}, 结束日期: {}", userId, startOfMonth, endOfMonth);

        String reportContent = reportGenerationService.generateMonthlyReport(userId, startOfMonth, endOfMonth);
        
        // 获取统计信息
        List<WorkRecordResponse> records = workRecordService.getWorkRecordsByDateRange(userId, startOfMonth, endOfMonth);
        int totalTimeSpent = records.stream().mapToInt(r -> r.getTimeSpent() != null ? r.getTimeSpent() : 0).sum();

        // 构建响应
        GeneratedReportResponse response = new GeneratedReportResponse(
                GenerateReportRequest.ReportType.MONTHLY, startOfMonth, endOfMonth, reportContent);
        response.setRecordCount(records.size());
        response.setTotalTimeSpent(totalTimeSpent);

        return ApiResponse.success(response, "本月月报生成成功");
    }

    /**
     * 生成指定日期的日报
     */
    @PostMapping("/generate/daily/{date}")
    @Operation(summary = "生成指定日期日报", description = "生成指定日期的工作日报")
    public ApiResponse<GeneratedReportResponse> generateDailyReportByDate(
            HttpServletRequest request,
            @Parameter(description = "日期", required = true) 
            @PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        
        Long userId = SecurityUtils.getCurrentUserId();
        logger.info("生成指定日期日报，用户ID: {}, 日期: {}", userId, date);

        String reportContent = reportGenerationService.generateDailyReport(userId, date);
        
        // 获取统计信息
        List<WorkRecordResponse> records = workRecordService.getWorkRecordsByDate(userId, date);
        int totalTimeSpent = records.stream().mapToInt(r -> r.getTimeSpent() != null ? r.getTimeSpent() : 0).sum();

        // 构建响应
        GeneratedReportResponse response = new GeneratedReportResponse(
                GenerateReportRequest.ReportType.DAILY, date, date, reportContent);
        response.setRecordCount(records.size());
        response.setTotalTimeSpent(totalTimeSpent);

        return ApiResponse.success(response, "日报生成成功");
    }
}
